import React, { memo, useEffect, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Form, Input, Modal, Table, Space, message, TablePaginationConfig } from "antd";
import { ResultEnum } from "@/enums/httpEnum";
import { getRoleList, deleteRole } from "@/api/modules/role";
import { IRole } from "@/api/interface/role";
import useCreateRole from "./hooks/useCreateRole";
import useGrantPermissionsToRole from "./hooks/useGrantPermissionsToRole";
import "./index.less";
import { convertTreeSelectData, TreeNode } from "@/utils/util";
import { IPermission } from "@/api/interface/permission";
import CustomTreeSelect from "@/components/CustomTreeSelect";

const { TextArea } = Input;

// eslint-disable-next-line react/display-name
const RoleManage = memo(() => {
	const [roleList, setRoleList] = useState<IRole[]>([]);
	const [total, setTotal] = useState(0);

	// 获取数据
	const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 });
	const getRoles = async () => {
		const { code, data } = await getRoleList(queryParams);
		if (code === ResultEnum.SUCCESS && data?.list.length) {
			setRoleList(data?.list);
			// setQueryParams({
			// 	...queryParams
			// });
			setTotal(data.total);
		}
		console.log(roleList);
		// setRoleList(res);
	};

	useEffect(() => {
		getRoles();
	}, []);
	// 新建框
	const { form, isModalOpen, submitting, onFinish, createModal, handleOk, editorForm, handleSubmit, handleCancel } =
		useCreateRole(getRoles);

	// 分配权限
	const {
		grantPermissionForm,
		isGrantPermissionModalOpen,
		grantPermissionSubmitting,
		permissionList,
		menuList,
		initPermissionIds,
		initMenuIds,
		setGrantPermissionModalOpen,
		handleGrantPermissionsSubmit,
		handleGrantPermissionsCancel,
		GrantPermissionsModalOpen,
		onSelectPermissionChange,
		menuOnchange
	} = useGrantPermissionsToRole();

	const { confirm } = Modal;
	const showConfirm = (id: number) => {
		confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "确定删除当前角色？此操作将会删除当前角色与它的全部子角色！",
			async onOk() {
				const { code, msg } = await deleteRole(id);
				if (code === 200) {
					message.success(msg);
					await getRoles();
				}
			},
			onCancel() {
				console.log("Cancel");
			}
		});
	};

	const columns: any[] = [
		{
			title: "角色名称",
			dataIndex: "name",
			key: "id",
			align: "center",
			width: 250
		},
		{
			title: "角色说明",
			dataIndex: "description",
			key: "description",
			align: "center"
		},
		{
			title: "创建人",
			dataIndex: "creator",
			key: "creator",
			align: "center",
			render: (creator: string, record: IRole) => {
				return (
					<div>
						{creator}
						{record.creatorName ? `(${record.creatorName})` : ""}
					</div>
				);
			}
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			width: 250
		},
		{
			title: "操作",
			dataIndex: "id",
			key: "id",
			width: 250,
			render: (id: number, record: IRole) => {
				return (
					<Space>
						<a onClick={() => editorForm(record)}>编辑</a>
						<a onClick={() => GrantPermissionsModalOpen(id)}>分配权限</a>
						<a onClick={() => showConfirm(id)}>删除</a>
					</Space>
				);
			},
			align: "center"
		}
	];

	// 切换分页
	useEffect(() => {
		getRoles();
	}, [queryParams]);

	const onTableChange = (pagination: TablePaginationConfig) => {
		setQueryParams({
			pageNum: pagination.current || 1,
			pageSize: pagination.pageSize || 10
		});
	};
	return (
		<div className="card role-manage-box">
			<div className="create">
				<Button type="primary" onClick={createModal}>
					添加角色
				</Button>
			</div>
			<Table
				bordered={true}
				dataSource={roleList?.map(item => {
					return {
						...item,
						key: item.id
					};
				})}
				columns={columns}
				rowKey={record => record.id}
				pagination={{
					total: total
				}}
				onChange={onTableChange}
			/>
			<Modal
				title="新建角色"
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button key="submit" type="primary" loading={submitting} onClick={handleSubmit}>
						确定
					</Button>
				]}
			>
				<Form<IRole> form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} layout="horizontal" onFinish={onFinish}>
					<Form.Item label="角色" name="name" rules={[{ required: true }]}>
						<Input />
					</Form.Item>
					<Form.Item label="角色描述" name="description" rules={[{ required: true }]}>
						<TextArea />
					</Form.Item>
				</Form>
			</Modal>
			<Modal
				title="分配权限"
				open={isGrantPermissionModalOpen}
				onOk={() => setGrantPermissionModalOpen(false)}
				onCancel={handleGrantPermissionsCancel}
				footer={[
					<Button key="back" onClick={handleGrantPermissionsCancel}>
						取消
					</Button>,
					<Button key="submit" type="primary" loading={grantPermissionSubmitting} onClick={handleGrantPermissionsSubmit}>
						确定
					</Button>
				]}
			>
				<Form form={grantPermissionForm} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} layout="horizontal">
					<Form.Item label="选择权限" name="permissions" rules={[{ required: true }]}>
						{isGrantPermissionModalOpen ? (
							<CustomTreeSelect
								onChange={onSelectPermissionChange}
								initialValues={initPermissionIds}
								treeData={convertTreeSelectData<TreeNode<IPermission>>(permissionList, (item: IPermission) => {
									return {
										title: item.name,
										key: item.id
									};
								})}
							/>
						) : null}
					</Form.Item>
					<Form.Item label="选择菜单" name="menuIds" rules={[{ required: true }]}>
						{isGrantPermissionModalOpen ? (
							<CustomTreeSelect
								onChange={menuOnchange}
								initialValues={initMenuIds}
								treeData={convertTreeSelectData<TreeNode<Menu.MenuOptions>>(menuList, (item: Menu.MenuOptions) => {
									return {
										title: item.title,
										key: item.id
									};
								})}
							/>
						) : null}
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
});
export default RoleManage;
